package com.crpc.runner;

import cn.hutool.core.util.ObjectUtil;
import com.crpc.common.annotation.CrpcService;
import com.crpc.factory.ProxyFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Slf4j
@Component
public class CrpcProxyBeanPostProcessor implements BeanPostProcessor {
    @Autowired
    ProxyFactory proxyFactory;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        for (Field field : bean.getClass().getDeclaredFields()) {
            CrpcService annotation = field.getAnnotation(CrpcService.class);
            if (ObjectUtil.isNotNull(annotation)) {
                Class<?> type = field.getType();
                field.setAccessible(true);
                try {
                    field.set(bean, proxyFactory.gerProxy(type));
                    log.info("代理接口是：{}", bean.getClass());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
